<template>
  <div class="login-wrap">
    <el-form label-position="top" ref="loginForm" label-width="80px" class="login-form" :model="formData" :rules="rules">
      <h1>用户登录</h1>
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username">
          <!-- 加自定义图标 -->
          <template #prefix>
            <el-icon class="el-input__icon">
              <i class="iconfont icon-user"></i>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input show-password v-model="formData.password">
          <!-- 加自定义图标 -->
          <template #prefix>
            <el-icon class="el-input__icon">
              <i class="iconfont icon-showpassword"></i>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-btn" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { message } from '@/utils/functions'
import { loginApi } from '@/api/login'
// 自定义密码的校验规则
const checkPassword = (rule, value, callback) => {
  value = value.trim()
  const reg = /^\w{3,}$/
  if (!reg.test(value)) {
    return callback(new Error('密码必须是3位以上由字母、数字、下划线组成的'))
  }
  callback()
}
// 表单数据
const formData = reactive({
  username: 'admin',
  password: '123456'
})
// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '密码长度最少3个以上', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: checkPassword, trigger: 'blur' }
  ]
})

// 定义dom
const loginForm = ref(null)
// 登录
const login = () => {
  // 验证表单
  loginForm.value.validate(async valid => {
    if (!valid) return
    // 验证通过
    // 登录
    /* try {
      const data = await loginApi(formData)
      message('success', '登录成功')
      console.log(data)
    } catch (err) {} */
    // const data = await loginApi(formData)
    message('success', '登录成功')
    console.log(data)
  })
}
</script>

<style lang="scss" scoped>
.login-wrap {
  position: relative;
  background-color: #324152;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  h1 {
    margin-top: 20px;
    font-size: 24px;
  }
  // 登录表单
  .login-form {
    background-color: #fff;
    width: 500px;
    padding: 30px;
    border-radius: 5px;
    // 提交按钮
    .login-btn {
      width: 100%;
    }
  }
}
</style>